package com.batch.demo.domain.flowDecisionDemo;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.flow.JobExecutionDecider;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FlowDecisionDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job flowDecisionDemoJob(){
        return jobBuilderFactory.get("flowDecisionDemoJob")
                .start(Step_1())
                .next(myDecider())
                .from(myDecider()).on("EVEN").to(Step_even())
                .from(myDecider()).on("ODD").to(Step_odd())
                // 无论返回什么都返回抉择器
                .from(Step_odd()).on("*").to(myDecider())
                .end()
                .build();

    }

//    @Bean
//    public Flow jobFlowDemoFlow1(){
//        return new FlowBuilder<Flow>("jobFlowDemoFlow1")
//                .start(jobFlowDemo2Step1())
//                .next(jobFlowDemo2Step2())
//                .build();
//    }

    // 决策器，用于复杂的判断
    @Bean
    public JobExecutionDecider myDecider(){
        return new MyDesicer();
    }

    @Bean
    public Step Step_1(){
        return stepBuilderFactory.get("Step_1")
               .tasklet(((stepContribution, chunkContext) -> {
                   System.out.println("Step_1");
                   return RepeatStatus.FINISHED;
               })).build();
    }

    @Bean
    public Step Step_odd(){
        return stepBuilderFactory.get("Step_odd")
                .tasklet(((stepContribution, chunkContext) -> {
                    System.out.println("Step_odd");
                    return RepeatStatus.FINISHED;
                })).build();
    }

    @Bean
    public Step Step_even(){
        return stepBuilderFactory.get("Step_even")
                .tasklet(((stepContribution, chunkContext) -> {
                    System.out.println("Step_even");
                    return RepeatStatus.FINISHED;
                })).build();
    }

}
